<template>
  <div>
    <!-- 面包屑导航 -->
    <div>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 搜索框 -->
    <div>
      <el-input placeholder="请输入内容" v-model="userinfo"  @keydown.native.enter="queryUser"  class="input-with-select" style="width: 300px;">
        <el-button slot="append" icon="el-icon-search" @click="queryUser"></el-button>
      </el-input>
      <el-button type="primary" plain @click="addDialogFormVisible = true">添加用户</el-button>
    </div>
     <!-- 用户列表表格 -->
     <div class="mb-15 mt-15">
       <el-table
        ref="singleTable"
        :data="userList"
        v-loading="loading"
        border
        highlight-current-row
        style="width: 100%">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          property="username"
          label="账号">
        </el-table-column>
        <el-table-column
          property="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          property="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          label="是否切换状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="Statechange(scope.row)"
              active-color="#409EFF"
              inactive-color="#cccccc">
            </el-switch>
           </template>
        </el-table-column>
        <el-table-column
          label="用户编辑">
           <template slot-scope="scope">
              <el-button type="primary" plain icon="el-icon-edit" @click="SingleData(scope.row)"></el-button>
              <el-button type="warning" plain icon="el-icon-delete" @click="deluser(scope.row)"></el-button>
              <el-button type="success" plain icon="el-icon-check" @click="roleData1(scope.row)"></el-button>
           </template>
        </el-table-column>
      </el-table>
     </div>
     <!-- 分页 -->
     <div class="page">
       <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalnum">
      </el-pagination>
     </div>
     <!-- 添加用户弹窗 -->
     <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
        <el-form :model="myaddform" :rules="rules" ref="adduserFrom">
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input v-model="myaddform.username" placeholder="请输入用户名" autoComplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
            <el-input v-model="myaddform.password" placeholder="请输入6-8位数字跟字母或则符号混合的密码" type="password" autoComplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input v-model="myaddform.email" placeholder="请输入邮箱" autoComplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
            <el-input v-model="myaddform.mobile" placeholder="请输入手机号码" autoComplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="adduser('adduserFrom')">确 定</el-button>
        </div>
    </el-dialog>
    <!-- 编辑用户弹窗 -->
     <el-dialog title="编辑用户" :visible.sync="EditDialogFormVisible">
        <el-form :model="SingleInfo" :rules="rules" ref="EaituserFrom">
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input
              v-model="SingleInfo.username"
              style="width: 120px"
              :disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input v-model="SingleInfo.email" placeholder="请输入邮箱" autoComplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
            <el-input v-model="SingleInfo.mobile" placeholder="请输入手机号码" autoComplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="EditDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="Edituser('EaituserFrom')">确 定</el-button>
        </div>
    </el-dialog>
    <!-- 角色权限弹窗 -->
     <el-dialog title="角色授权" :visible.sync="DictionDialogFormVisible">
        <el-form :model="Diction" :rules="rules">
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input
              v-model="Diction.username"
              style="width: 120px"
              :disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth">
              <el-select v-model="Diction.cid">
                <!--
                  label用来控制下拉选择器展示在页面中的文字
                  value用来获取点击label文字之后，获取到的当前角色的角色id
                -->
                <el-option
                  v-for="(itme,index) in roleData"
                  :key="index"
                  :label="itme.roleName"
                  :value="itme.id">
                </el-option>
              </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="DictionDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="allocation">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { userdata, delteUser, AddUserinfo, EditInfo, Switchover, Casting, distribute } from '@/api'
export default {
  data () {
    // 密码验证
    var pasw = (rule, value, callback) => {
      // 定义一个验证密码正则
      // eslint-disable-next-line
        let verifyPasw = /^[a-zA-Z]\w{5,17}$/
      if (!value) {
        return callback(new Error('密码不能为空'))
      }
      if (!verifyPasw.test(value)) {
        return callback(new Error('密码格式错误'))
      } else {
        callback()
      }
    }
    // 邮箱验证
    var Eal = (rule, value, callback) => {
      // eslint-disable-next-line
      let verifyEal = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      if (!verifyEal.test(value)) {
        return callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    // 用户名验证
    var UserNameinfo = (rule, value, callback) => {
      let verifyName = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
      if (!value) {
        return callback(new Error('用户名不能为空'))
      }
      if (!verifyName.test(value)) {
        return callback(new Error('用户名格式出错'))
      } else {
        callback()
      }
    }
    // 手机号验证
    var phone = (rule, value, callback) => {
      let veriftPhone = /^(13[0-9]|14[0-9]|15[0-9]|166|17[0-9]|18[0-9]|19[8|9])\d{8}$/
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      if (!veriftPhone.test(value)) {
        return callback(new Error('手机号出错'))
      } else {
        callback()
      }
    }
    return {
      loading: true, // 这是加载菊花的东西
      userinfo: '', // 用户搜素框，
      totalnum: 0, // 总条数
      pagesizes: 5, // 默认每页条数是5条
      pagemun: 1, // 默认是第一页
      userList: [], // 这是全部用户的数据
      addDialogFormVisible: false, // 添加用户弹框隐藏显示的条件
      EditDialogFormVisible: false, // 编辑用户弹框隐藏显示的条件
      // 需要提交新增用户的信息
      myaddform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑单个用户数据
      SingleInfo: {
        // eslint-disable-next-line
        id:0,
        // eslint-disable-next-line
        mobile: '',
        // eslint-disable-next-line
        username:'',
        // eslint-disable-next-line
        email:'',
      },
      // 表单校验规则
      rules: {
        username: [
          { required: true, validator: UserNameinfo, trigger: 'blur' }
        ],
        password: [{ required: true, validator: pasw, trigger: 'blur' }],
        email: [{ required: true, validator: Eal, trigger: 'blur' }],
        mobile: [{ required: true, validator: phone, trigger: 'blur' }]
      },
      // 角色权限信息
      DictionDialogFormVisible: false,
      Diction: {
        username: '',
        id: '',
        cid: ''// 用来保存用户选中角色之后的角色id，将来传给后台
      },
      // 获取角色
      roleData: [],
      formLabelWidth: '120px' // 添加用户输入宽的宽度
    }
  },
  created () {
    this.usersData()
  },
  methods: {
    // 切换条数
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      // 把每页显示的条数赋值给pagesizes
      this.pagesizes = val
      // 再次渲染页面
      this.usersData()
    },
    // 切换页数
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      // 把当即的页数赋值给pagemun
      this.pagemun = val
      // 再次渲染页面
      this.usersData()
    },
    // 获取用户数据
    usersData () {
      // 获取数据方法
      userdata({
        params: {
          query: this.userinfo,
          pagenum: this.pagemun,
          pagesize: this.pagesizes
        }
      }).then(res => {
        // console.log(res)
        this.userList = res.data.users
        this.totalnum = res.data.total
        setTimeout(() => {
          this.loading = false
        }, 500)
      })
    },
    // 用户搜索方法
    queryUser () {
      // console.log(this.userinfo)
      this.usersData()
      this.userinfo = ''
    },
    // 删除用户操作
    deluser (row) {
      // 为了增加用户体验感，防止用户点错删除按钮
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 当点击确定删除的时候我们则删除
        // console.log(typeof row.id)
        delteUser(row.id).then(res => {
          // console.log(res)
          if (res.meta.status === 200) {
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
            // 判断删除之后是否当前的页数的是否还有条数
            let pages = this.userList.length % this.pagesizes
            console.log(pages)
            if (pages === 1) {
              // console.log(this.pagemun)
              // 回到上一页，再重新加载页面
              this.pagemun = this.pagemun - 1
              this.usersData()
            } else {
              // 重新加载页面
              this.usersData()
            }
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取单个用户数据
    SingleData (row) {
      console.log(row)
      // 赋值给存放编辑单个用户信息中
      this.SingleInfo.username = row.username
      this.SingleInfo.id = row.id
      this.SingleInfo.email = row.email
      this.SingleInfo.mobile = row.mobile
      // 显示编辑用户的弹窗
      this.EditDialogFormVisible = true
    },
    // 添加用户--点击确定的按钮
    adduser (adduserFrom) {
      this.$refs[adduserFrom].validate(valid => {
        if (valid) {
          // alert('submit!')
          AddUserinfo(this.myaddform)
            .then(res => {
              // console.log(res)
              if (res.meta.status === 201) {
                this.$message({
                  message: res.meta.msg,
                  type: 'success'
                })
                // 隐藏添加用户表单
                this.addDialogFormVisible = false
                // 清空表单的值
                this.myaddform.username = ''
                this.myaddform.password = ''
                this.myaddform.email = ''
                this.myaddform.mobile = ''
                // 重新加载页面,返回第一页
                this.pagemun = 1
                this.usersData()
              }
            })
        } else {
          this.$message({
            message: '表单校验出错，请检查',
            type: 'error'
          })
          return false
        }
      })

      // AddUserinfo
    },
    // 编辑单个用户数据
    Edituser (EaituserFrom) {
      this.$refs[EaituserFrom].validate((valid) => {
        if (valid) {
          // console.log(this.SingleInfo.id)
          EditInfo(this.SingleInfo.id, this.SingleInfo)
            .then(res => {
              console.log(res)
              if (res.meta.status === 200) {
                this.$message({
                  showClose: true,
                  message: res.meta.msg,
                  type: 'success'
                })
                this.EditDialogFormVisible = false
                this.usersData()
              } else {
                this.$message({
                  showClose: true,
                  message: res.meta.msg,
                  type: 'warning'
                })
                this.EditDialogFormVisible = false
              }
            })
        } else {
          this.$message({
            showClose: true,
            message: '编辑用户表单校验未通过,请检查',
            type: 'warning'
          })
          return false
        }
      })
    },
    // 切换用户状态
    Statechange (row) {
      Switchover(row)
        .then(res => {
          console.log(res)
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg)
          } else {
            this.$message.error(res.meta.msg)
          }
        })
    },
    // 修改权限信息
    roleData1 (row) {
      this.DictionDialogFormVisible = true
      this.Diction.username = row.username
      this.Diction.id = row.id
      this.Diction.cid = row.role_name
      // console.log(row)
      // 获取角色列表
      Casting()
        .then(res => {
          // console.log(res)
          this.roleData = res.data
        })
    },
    // 角色分配点击按钮
    allocation () {
      if (typeof this.Diction.cid === 'string') {
        this.$confirm('你还没有修改到角色分配哦,是否确定？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.DictionDialogFormVisible = false
          return false
        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '已返回修改页面'
          })
        })
      } else {
        distribute(this.Diction)
          .then(res => {
            console.log(res)
            if (res.meta.status === 200) {
              this.$message.success('角色分配修改成功')
              this.DictionDialogFormVisible = false
              this.usersData()
            }
          })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
